package api

import (
	"bytes"
	"io"
	"lion-passport/internal/controller"
	"lion-passport/internal/middleaware"
	"os"
	"time"

	"github.com/gin-gonic/gin"

	log "github.com/sirupsen/logrus"
)

func SetupRouter() *gin.Engine {
	// 创建日志文件（追加模式）
	f, _ := os.OpenFile("lion-app.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)

	// 设置日志输出（同时输出到文件和控制台）
	gin.DefaultWriter = io.MultiWriter(f, os.Stdout)
	r := gin.Default()
	r.Use(RequestLogger()) // 使用自定义的请求日志中间件

	// Define the API routes
	api := r.Group("/api/v1")
	{
		// 用户登录
		api.POST("/user/login", controller.LoginHandler)
		api.POST("/user/token/refresh", controller.TokenRefreshHandler)

		authed := api.Group("/")
		authed.Use(middleaware.AuthMiddleware()) // 使用认证中间件
		{
			authed.POST("/user/create", controller.CreateUserHandler) // 创建用户
			authed.GET("/user/info", controller.GetUserByIdHandler)   // 获取用户信息
			authed.POST("/user/update", controller.UpdateUserHandler) // 更新用户信息
		}
	}

	return r
}

func RequestLogger() gin.HandlerFunc {
	return func(c *gin.Context) {
		start := time.Now()

		// 读取请求体（会清空，所以要复制）
		var bodyBytes []byte
		if c.Request.Body != nil {
			bodyBytes, _ = io.ReadAll(c.Request.Body)
		}
		c.Request.Body = io.NopCloser(bytes.NewBuffer(bodyBytes)) // 恢复请求体供后续使用

		// 捕获响应体
		respBody := new(bytes.Buffer)
		writer := &responseWriter{body: respBody, ResponseWriter: c.Writer}
		c.Writer = writer

		// 处理请求
		c.Next()

		duration := time.Since(start)

		log.Infof("➡️  %s %s | Params: %s | Status: %d | Duration: %v | Response: %s\n",
			c.Request.Method,
			c.Request.URL.Path,
			string(bodyBytes),
			c.Writer.Status(),
			duration,
			respBody.String(),
		)
	}
}

// 自定义的 ResponseWriter 结构体，用于捕获响应内容
type responseWriter struct {
	gin.ResponseWriter
	body *bytes.Buffer
}

func (rw *responseWriter) Write(p []byte) (int, error) {
	rw.body.Write(p)
	return rw.ResponseWriter.Write(p)
}
